package com.ctg.itrdc.imageconsole.service.scheduler;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.constants.AutoElasticConstant;
import com.ctg.itrdc.imageconsole.data.dao.IAutoscalePolicyDao;
import com.ctg.itrdc.imageconsole.data.dao.IClusterConfigDao;
import com.ctg.itrdc.imageconsole.data.entity.AutoscalePolicy;
import com.ctg.itrdc.imageconsole.data.entity.DockerMicroService;
import com.ctg.itrdc.imageconsole.service.IAutoElasticService;

/**
 * 
 * @description: 定时调度器，入口
 * @version: v1.0.0
 * @author: Piao.Wu
 * 
 *          Modification History: Date Author Version Description
 *          -----------------------------------------------------------------
 *          2016年11月8日 下午3:09:38 Piao.Wu v1.0.0 create
 *
 */
@Component("schedulerBootstrap")
@Lazy(value = false)
public class SchedulerBootstrap {

	private static final long INTERVAL_10 = 10L;

	private ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1);

	@Resource(name = "checkExecutingRecordsScheduler")
	private IScheduler checkExecutingRecordsScheduler;
	@Resource
	private IAutoElasticService autoElasticService;
	@Resource
	private IAutoscalePolicyDao autoscalePolicyDao;
	@Resource
	private IClusterConfigDao clusterConfigDao;

	@PostConstruct
	public void start() {
		// scheduledExecutor.scheduleWithFixedDelay((Runnable)
		// checkExecutingRecordsScheduler, 0, INTERVAL_10,
		// TimeUnit.SECONDS);

		startAutoScaleByTime();
	}

	private void startAutoScaleByTime() {
		// 项目启动时，检查所有需要启动的以时间周期为指标的自动伸缩任务的服务，并启动定时任务
		List<DockerMicroService> microServices = autoElasticService.getNeedAutoScaleServices();
		for (DockerMicroService microService : microServices) {
			AutoscalePolicy autoscalePolicy = autoscalePolicyDao.selectById(microService.getAutoscalePolicyId());
			if (!AutoElasticConstant.ELASTIC_INDICATOR_TIME.equals(autoscalePolicy.getElasticIndicator())) {
				continue;
			}
			String apiServerUrl = clusterConfigDao.selectApiServerUrlByClusterCode(microService.getK8sCode());
			autoElasticService.startAutoElasticJobForTime(apiServerUrl, microService.getNamespace(),
					microService.getDpName(), autoscalePolicy, microService.getCreateUserId());
		}
	}

}
